<template>
  <!-- :style="{ minHeight: appHeight + 'px' }" -->
  <div class="app nut-navbar--safe-area-inset-top nut-tabbar-safebottom" onselectstart="return false;">
    <!-- <div class="app_bg"></div> -->
    <nut-navbar v-if="state.hasHeader" class="navbar" z-index="5" :clickable="false">
      <template #content>
        <span>{{ state.title }}</span>
      </template>
      <template #left>
        <iconpark-icon @click="onClickLeft" class="close" name="back" size="1.2rem"></iconpark-icon>
      </template>
      <template #right>
        <div class="amount_box" v-if="hasLogin">
          <iconpark-icon class="close" icon-id="dong1" size="1.2rem"></iconpark-icon>
          <span>
            <nut-price :price="convert2DisplayMoney(roleInfo.money)" size="small" style="color: #ffd56d"
              :decimal-digits="0" thousands :need-symbol="false" /></span>
          <iconpark-icon @click="router.push('deposit')" class="close" icon-id="add" size="1.2rem"></iconpark-icon>
        </div>
      </template>
    </nut-navbar>

    <router-view v-slot="{ Component, route }">
      <transition>
        <component :is="Component" :key="route.path" />
      </transition>
    </router-view>

    <nut-tabbar z-index="2" v-if="state.hasTabbar" route v-model="state.active" bottom placeholder
      :before-switch="beforeSwitch">
      <nut-tabbar-item class="item" :name="item.name" @click.stop="tabbarClick(item)"
        v-for="(item, i) in state.tablebarArr" :key="i">{{ t(item.text) }}
        <template #icon="props">
          <span class="tt" v-if="item.isWallet" id="pop_target">
            <SvgaItem :keyStr="i" name="jinbi" :active="state.popoverShow" :loopNumber="1" class="tabbar_icon_1" />
          </span>
          <nut-badge :dot="!!(item.name == 'me' && page.unread)" v-else-if="item.isMe">
            <iconpark-icon :icon-id="props.active ? item.active : item.unactive" size="1.4rem"></iconpark-icon>
            <!-- <SvgaItem :keyStr="i" :name="item.name" :active="props.active" :loopNumber="1" class="tab_style" /> -->
          </nut-badge>
          <iconpark-icon :icon-id="props.active ? item.active : item.unactive" size="1.4rem" v-else></iconpark-icon>
          <!-- <SvgaItem :keyStr="i" :name="item.name" :active="props.active" :loopNumber="1" class="tab_style" v-else /> -->
        </template>
      </nut-tabbar-item>
    </nut-tabbar>

    <div class="popover_bg" :class="`${state.popoverShow && 'pop_height'}`">
      <div v-for="(v, j) in state.walletList" :key="j" @click="onClickToPage(v)">
        <ImgT :src="v.img" :alt="v.text" />
        <span>{{ t(v.text) }}</span>
      </div>
    </div>

    <nut-overlay v-model:visible="isPopShow" :close-on-click-overlay="false" :lock-scroll="true" :overlay-style="{
      backgroundColor: 'rgba(0, 0, 0, .5)',
    }">
      <div class="login_pop">
        <Login v-if="isLogin"></Login>
        <!-- 注册弹窗 -->
        <Register v-if="isReg" />
        <!-- 注册退出弹窗 -->
        <RegisterQuit v-if="isRegQuit" />
        <ForgotPassword v-if="isForget"></ForgotPassword>
      </div>
    </nut-overlay>

    <!-- 公告弹窗 -->
    <Notice ref="noticeRef" />
    <!-- 异地登录 -->
    <Modal :title="t('home_page_diffOfflineTitle')" :visible="diffOfflineObj.show" :showClose="false">
      <div class="diff_offline_dialog">
        <div>{{ diffOfflineObj.content }}</div>
        <div class="btn" @click="diffOfflineObj.show = false">{{ t("confirm") }}</div>
      </div>
    </Modal>
  </div>
  <nut-overlay v-model:visible="state.show">
    <div class="overlay_body">
      <SvgaItem keyStr="xz" name="xz" :active="true" style="width: 20vw; height: 20vw" class="overla_content" />
    </div>
  </nut-overlay>
  <!-- 左侧侧滑页面 -->
  <nut-popup v-model:visible="showLeft" :overlay="true" :lock-scroll="true" position="left"
    :style="{ width: '100%', height: '100%', marginTop: '16% ' }">
    <category></category>
  </nut-popup>

  <OverLoading v-model:visible="gameIsLoading"></OverLoading>
</template>
<script setup lang="ts">
import Modal from "@/components/Modal.vue";
import { computed, onMounted } from "vue";
import { watch, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import Login from "@/components/Login.vue";
import Register from "@/components/Register.vue";
import RegisterQuit from "@/components/RegisterQuit.vue";
import ForgotPassword from "@/components/ForgotPassword.vue";
import OverLoading from "@/components/Loading.vue";
import pinia from "@/store/index";
import { storeToRefs } from "pinia";
import { User } from "@/store/user";
import { Page } from "@/store/page";
import { MessageEvent2 } from "./net/MessageEvent2";
import { NetMsgType } from "./netBase/NetMsgType";
// import { NetEnumDef } from "./netBase/NetEnumDef";
// import { needLoginApi } from "@/utils/useNetMethods";
import { NetPacket } from "./netBase/NetPacket";
// import { Net } from "@/net/Net";
import H5Websocket from "@/net/Net1";
import { onBeforeMount } from "vue";
import Notice from "@/components/Notice.vue";
import { bankPayMethods, bankPayType, convertObjectToDateString } from "./utils/publicMethods";
import { useI18n } from "vue-i18n";
import { showDialog, showNotify, showToast } from "@nutui/nutui";
import SvgaItem from "@/components/SvgaItem.vue";
// import freeHuntModal from "@/components/freeHuntModal.vue"
import category from "@/views/category/index.vue";
import { convert2DisplayMoney, getIPAddress, unserialize } from "@/utils/useStoreMethods";
import { getLocale } from "./main";
import { Local } from "./utils/storage";

const { settings, gameIsLoading, showLeft, homeGameData } = storeToRefs(Page(pinia));
const { allCollected, hasLogin, shopInfoData, bankCardInfoList } = storeToRefs(User(pinia));
const { t } = useI18n();
// const Login = defineAsyncComponent(() => import("@/components/Login.vue"))
const page = Page(pinia);
const isPopShow = computed(
  () => isLogin.value || isReg.value || isRegQuit.value || isForget.value
);
const { isLogin, isReg, isRegQuit, isForget, roleInfo, myEmail } = storeToRefs(
  User(pinia)
);
const route = useRoute();
const router = useRouter();
const state: any = reactive({
  isMainDeposit: false, // 是否全部充值方式都维护
  isMainWidthdraw: false, // 是否全部提现方式都维护
  show: false,
  popoverShow: false,
  active: "home",
  hasHeader: false,
  hasTabbar: true,
  title: '',
  leftIcon: "",
  rightIcon: "",
  routeName: "home",
  tablebarArr: [
    {
      text: "route_page_home",
      name: "home",
      active: "home",
      unactive: "home1",
      url: "/",
      show: false,
      id: 1,
    },
    {
      text: "route_page_category",
      name: "category",
      active: "category",
      unactive: "category1",
      url: "",
      show: false,
      id: 2,
    },
    {
      text: "route_page_transaction",
      name: "",
      active: "",
      unactive: "",
      url: "",
      isWallet: true,
      show: false,
      id: 3,
    },
    {
      text: "route_page_activity",
      name: "activity",
      active: "activity",
      unactive: "activity1",
      url: "/activity",
      show: false,
      id: 4,
    },
    {
      text: "route_page_me",
      name: "me",
      active: "me",
      unactive: "me1",
      url: "/me",
      isMe: true,
      show: false,
      id: 5,
    },
  ],
  walletList: [
    {
      text: "route_page_wallet",
      img: "/imgs/tabbar/qb.webp",
      url: "/myWallet",
    },
    {
      text: "route_page_deposit",
      img: "/imgs/tabbar/cz.webp",
      url: "/deposit",
      key: "deposit",
    },
    {
      text: "route_page_withdrawals",
      img: "/imgs/tabbar/tx.webp",
      url: "/withdrawals",
      key: "withdrawals",
    },
  ],
});

const onClickLeft = () => {
  if (String(route.name) == 'gameDetail') {
    Local.remove("agentId");
    router.push("/");
  } else {
    router.go(-1);
  }

};
// const onClickRight = () => {
//   switch (route.name) {
//     default: ;
//       break;
//   }
// };
// const onClickRight1 = () => {
//   router.push('/')
// }



const onClickToPage = (item: any) => {
  state.popoverShow = false;
  // 充值维护
  if (item?.key === 'deposit' && state.isMainDeposit) {
    return
  }
  // 提现维护
  if (item?.key === 'withdrawals' && state.isMainWidthdraw) {
    return
  }
  router.push(`${item.url}`);
};
const beforeSwitch = (item: any) => {
  if (!item.name) {
    state.popoverShow = !state.popoverShow;
    state.active = "";
    return false;
  } else {
    state.popoverShow = false;
    state.active = item.name;

    router.push(item.to);
    return false;
  }
};
const leftIcon = (name: string) => {
  switch (name) {
    case "home":
      return "bars";

    default:
      return "tongyicontyfanh";
  }
};
const rightIcon = (name: string) => {
  switch (name) {
    case "name":
      return "";
    default:
      return "service";
  }
};
const title = (name: string) => {
  if (name == 'gameDetail') {
    const data = homeGameData.value.find((e: any) => e.id == Number(route.query.venue_id));
    return unserialize(data.name, false); // name as strin
  } else {
    return t(String(route.meta.title))
  }
}
const init = (name: string) => {
  //头部导航不显示
  state.hasHeader = ![
    "home",
    "insidePages",
    "activity",
    "me",
    "vip",
    "trans",
    "myWallet",
    "undefined",
    "openGame",
    "chatList",
    "chatRoom",
    "friendsList",
    "clubCreate",
    "record",
    "category",
    "hotGameDetail",
    "searchGames",
    'member',
    'club',
    'myClub',
    'approvalMenber',
    'allMember',
    'clubDetail',
    'handList',
    'eventDetails',
    'clubHandList',
    'game'
  ].includes(String(name));
  // 底部tabBar不显示
  state.hasTabbar = ![
    "undefined",
    "chatList",
    "chatRoom",
    "friendsList",
    "shortcut",
    "openGame",
    "freeLoot",
    "hotGameDetail",
    "searchGames",
    'club',
    'myClub',
    'approvalMenber',
    'allMember',
    'clubDetail',
    'handList',
    'eventDetails',
    'clubHandList',
    "activityDetail"
  ].includes(String(name));

  // state.hasTabbar = ['home', 'activity', 'me', 'vip', 'trans'].includes(String(name))
  state.leftIcon = leftIcon(name);
  state.rightIcon = rightIcon(name);
  state.title = title(name)
  state.active = name;
};

// 公告消息
const noticeRef = ref();
const onHander_system_notice = async (message: any) => {
  if (message.notice_list?.length) {
    const dialogList: any = message.notice_list.filter((item: any) => item.position == 1);
    const paomaList: any = message.notice_list.filter((item: any) => item.position == 0);

    // 弹窗公告
    let localIds = []; // 本地记录的不再显示
    try {
      localIds = JSON.parse(localStorage.getItem("readed_notice_ids") || "[]");
    } catch {
      localIds = [];
    }
    const list: any = dialogList
      .filter((item: any) => !localIds.includes(item.title))
      .sort((a: any, b: any) => {
        return b.priority - a.priority;
      });
    if (list.length) {
      await getLocale(settings.value);
      await User(pinia).setNoticeList(list);
      User(pinia).setNotice(true);
      noticeRef.value.open();
    }

    // 轮播公告
    paomaList.forEach((item: any) => {
      page.setTextAnnouncementMore(t(item.title) + " - " + t(item.content));
    });
  }
};

// setTimeout(() => {
//   onHandler_system_msg({
//     code: 903,
//     Params: ['1', '1', 'system_notice_title_58', 'system_notice_content_58', '1'],
//     priority: 0,
//     type: 1
//   })
// }, 5000)

// 消息通知
const onHandler_system_msg = async (m: any) => {
  // console.error('----系统消息', m)
  if (m.code == 903) {
    if (m.Params[0] == 1) {
      // 弹窗公告
      try {
        const list: any = [
          {
            content: `${m.Params[3]}`,
            title: `${m.Params[2]}`,
            position: 1,
            priority: m.priority,
            type: m.Params[1],
          },
        ];
        await getLocale(settings.value);
        await User(pinia).setNoticeList(list);
        User(pinia).setNotice(true);
        noticeRef.value.open();
      } catch {
        console.error("error msg", m);
      }
    }
  } else {
    if (m.Params && m.Params.length == 6) {
      // 跑马灯
      // ***[0]*** 在 [3] 获得 [4] 金币奖励！
      const str = t("home_notice_mixtext", {
        user: `${m.Params[0]?.substr(0, 4)}***`,
        game: m.Params[3] ? t(m.Params[3]) : "",
        money: m.Params[4] ? Number(m.Params[4]).toLocaleString() : 0,
      });
      page.setTextAnnouncementMore(str);
    }
  }

  if (m.code == 901) {
    if (m.Params && m.Params.length == 6) {
      // 高分跑马灯
      // ***[0]*** 在 [3] 获得 [4] 金币奖励！
      const str = t("home_notice_mixtext", {
        user: `${m.Params[0]?.substr(0, 4)}***`,
        game: m.Params[3] ? t(m.Params[3]) : "",
        money: m.Params[4] ? Number(m.Params[4]).toLocaleString() : 0,
      });
      page.setTextAnnouncementMore(str);
    }
  }
};

// 异地登录
const diffOfflineObj: any = ref({
  show: false,
  content: "",
});
const getDeviceType = (device_id: any) => {
  if (device_id == 1) return "WEB";
  if (device_id == 2) return "Android";
  if (device_id == 3) return "IOS";
  return t("else");
};
const diffOfflineFunc = async (res: any) => {
  // 您的账号上次在2024-05-28 19:20:02于xx的xx设备登录，如非本人操作，则密码可能泄露，建议您修改密码
  console.error("异地登录", res);
  // let ipText = res.ip;
  (res.ip) && await getIPAddress([res]) //  await getIP(res.ip);

  diffOfflineObj.value.show = true;
  diffOfflineObj.value.content = t("home_page_diffOfflineContent", {
    time: convertObjectToDateString(res.login_time),
    device: res.device_id ? getDeviceType(res.device_id) : "",
    ip: res.location,
  });
};


// 我的邮箱
const emailList: any = [];
let email_id_list: any = [];
const handleEmailInfo = async (rs: any) => {
  if (rs.emails.length > 0) {
    if (!email_id_list.includes(rs.emails[0].email_id)) {
      emailList.push(rs.emails[0]);
    }
    if (emailList.length > 0) {
      email_id_list = emailList.map((item: any) => item.email_id);
    }
    const sb = new Set(rs.email_readed);
    emailList.forEach((item: any) => {
      const timer = convertObjectToDateString(item.recv_time);
      item.time = new Date(timer).getTime();
    });

    emailList.sort((a: any, b: any) => b.time - a.time); // 排序
    const list = emailList.filter((item: any) => item.attachments[0].award_value == 0);
    const rewardList = emailList.filter(
      (item: any) => item.attachments[0].award_value > 0
    );
    const params = {
      email_readed: rs.email_readed,
      list,
      rewardList,
      email_id_list,
      hasNoRead: email_id_list.some((x: any) => !sb.has(x)),
    };
    await User(pinia).setEmailList(params);
  }
};

// 监听新收到邮箱
const handleNewEmail = (rs: any) => {
  //奖励邮箱
  if (rs.new_email.attachments[0].award_value > 0) {
    myEmail.value.rewardList.unshift(rs.new_email);
  } else {
    myEmail.value.list.unshift(rs.new_email);
  }
  myEmail.value.hasNoRead = true;
};



// 角色详情
const handleRoleInfo = async (data: any) => {
  await User(pinia).getRoleInfo(data);
};
// 角色VIP详情
const handleVipInfo = async (data: any) => {
  await User(pinia).getVIPInfo(data);
};
// 用户详情
const handleUserInfo = async (data: any) => {
  console.error("---登录返回", data);
  await User(pinia).getInfo(data);
  await User(pinia).setHasLogin(true);

  getFirstStatus();
};
// 登录成功后发送邀请码
const handleLoginFinish = async (data: any) => {
  if (data.result == 1) {
    const agent_id = localStorage.getItem("agent_id");
    if (Number(agent_id)) {
      const rq = NetPacket.req_set_invitecode();
      rq.superior_id = Number(agent_id);
      // Net.instance.sendRequest(rq)
      H5Websocket.sendMessageHandler(rq);
    }
  }
};

// 监听金额变化
const handleUpdateMoney = async (data: any) => {
  if (data) {
    const newData = { ...roleInfo.value };
    newData.money = data.cur_money;
    await User(pinia).getRoleInfo(newData);
  }
};
// 余额变化
const handleUpdateRoleInfo = async (data: any) => {
  if (data?.id) {
    console.log("update-roleInfo---", data);
    // 因为这里返回的数据缺少了很多字段，所以需要这样处理
    const newData = {
      ...roleInfo.value,
      ...data,
    };
    await User(pinia).getRoleInfo(newData);
  }
};
// 获取充值信息
const getShopInfo = () => {
  const req = NetPacket.req_get_shop_info();
  H5Websocket.sendMessageHandler(req);
};
// 获取已绑定的银行账号
const getMyBankList = () => {
  const req = NetPacket.req_bank_card_info_list();
  H5Websocket.sendMessageHandler(req);
}
// 打开侧滑页面
const tabbarClick = (item: any) => {
  // 充提
  if ([3].includes(item.id)) {
    state.popoverShow = !state.popoverShow;
    if (state.popoverShow && hasLogin.value) {
      getShopInfo();
      getMyBankList();
    }
  }
  if ([2, 5].includes(item.id)) {
    if (!hasLogin.value) {
      isLogin.value = true;
      state.active = "home";
      return;
    }
  }
  if (item.id == 2) {
    if (hasLogin.value) {
      router.push("/");
      setTimeout(() => {
        showLeft.value = item.id == 2;
      }, 60);
    }
  }
  router.push(item.url);
};

if (location.href.includes('?relogin=1') && !Local.get('user')) {
  setTimeout(() => {
    User(pinia).setLogin(true);
  }, 1000)
}
// 重复登录
MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_repeat_login, async () => {
  Local.remove("user");
  await User(pinia).setHasLogin(false);
  showDialog({
    title: t("home_page_offlineNotification"),
    content: t("home_page_offlineContent"),
    okText: t("home_page_offlineConfirm"),
    cancelText: t("home_page_modifyPassword"),
    onOk: async () => {
      location.href = '/?relogin=1';
    },
    onCancel: async () => {
      location.href = '/?relogin=1';
    },
  });
});
// 充值成功，弹出提示
const handleDepositSuc = async (data: any) => {
  if (data?.amount) {
    showNotify.success(t("deposit_page_depSuccess")); // 充值成功需要弹出提示
  } else {
    showNotify.danger(t("deposit_page_depSuccess"));
  }
};
const resizeChange = () => {
  if (window.orientation === 90 || window.orientation === -90) {
    state.show = true;
  } else {
    state.show = false;
  }
};
// 获取所有收藏的游戏id集合
const resAllCollect = async (data: any) => {
  await User(pinia).getCollected(data.collected);
};
// 是否收藏游戏
const resCollect = async (data: any) => {
  if (data.rlt == 0) {
    let gameId = Local.get("gameId");
    if (allCollected.value.includes(gameId) || gameId === 'COLLECT_CANCEL') {
      let arr = allCollected.value.filter((e: Number) => e != gameId);
      await User(pinia).getCollected(arr);
      showToast.success(t("collect_success_cancel"));
    } else {
      let arr = [...allCollected.value, gameId];
      await User(pinia).getCollected(arr);
      showToast.success(t("collect_success"));
    }
  } else if (data.rlt == 1) {
    showToast.warn(t("collect_success_limit"));
  } else {
    showToast.fail(t("Unknown_error"));
  }
};
// 游戏返回的链接
// 第三方游戏信息返回

const handleFirstStatusApi = (res: any) => {
  // status = 0 无首充
  // status = 1 参与首充x3
  // status = 3 参与首充100%
  sessionStorage.setItem("FirstRechargeStatus", res.status);
};

const gameUrlResult = async (message: any) => {
  await Page(pinia).setGameIsLoading(false);
  if (message.code != 0) {
    showToast.fail(message.msg);
    return;
  }
  if (message.url.indexOf("<!doctype html>") != -1) {
    message.url = `data:text/html;charset=utf-8,${encodeURIComponent(
      String(message.url)
    )}`;
  }
  // document.removeEventListener('scroll', stopMove);
  // document.body.style.overflow = 'auto'
  // document.body.style.height = '200vh'
  // if ([23].includes(23)) {
  //   let newPage = window.open(message.url, '_blank');

  //   // newPage.document.write(data);//运行 HTML 代码
  //   newPage?.document.close();
  // } else {
  Local.set("gameUrl", message.url);
  router.push("/openGame");
  // }


};

// 获取首冲状态
const getFirstStatus = () => {
  const reqFirst = NetPacket.req_first_recharge_status();
  H5Websocket.sendMessageHandler(reqFirst);
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_first_recharge_status,
    handleFirstStatusApi
  );
};

const handleShopInfoRes = async (rs: any) => {
  // 匹配出银行的支付方式
  const newArr = [...rs.rechargelist_by_paymenttype].filter((item: any) => bankPayMethods.includes(item.paymenttype));
  // 为了赋值 payname 字段
  newArr.forEach((item: any) => {
    bankPayType.forEach((item_1: any) => {
      if (item.paymenttype === item_1.paymenttype) {
        item._payname = item_1.payname
      }
    })
  })
  console.log('newArr-----', newArr)
  const bankNewObj: any = newArr.find((item: any) => item.payname === 'bankcard');
  const bankAll: any = [];
  if (bankNewObj.paymethod) {
    bankNewObj.paymethod.split(',').map((item: any, index: any) => {
      bankAll.push({
        ...bankNewObj,
        paymethod: item, // 没有用到
        _paymenttype: 100 + index, // 银行转账 100,  网银直连 101， 扫码支付 102
        _payname: `bankcard_${index}`,
      })
    })
  }
  // 非银行的支付方式
  const notBankArr = newArr.filter((item: any) => item.payname !== 'bankcard').map((item: any) => { return { ...item, _paymenttype: item.paymenttype * 100 } });
  const allBankList = [...bankAll, ...notBankArr].map((item: any) => {
    return {
      ...item,
      label: t(`api_${item._payname}`),
      value: item._paymenttype,
    }
  });
  // 需要过滤 limit 为 0 的数据, .filter((item: any) => item.limit)
  const discountList = rs.discount_list.map((dc: any) => {
    return {
      ...dc,
      text: dc.name,
      label: dc.name,
      value: dc.discount_ID
    }
  })
  console.log('-------', discountList)
  const newObj: any = {
    ...rs,
    discount_list: discountList,
    rechargelist_by_paymenttype: allBankList,
  }
  await User(pinia).setShopInfoData(newObj);
};
const handleMyBankList = async (res: any) => {
  await User(pinia).setBankCardInfoData(res);
}


onBeforeMount(() => {
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_loading_end, async () => {
    await User(pinia).setLoadingEnd(true);
  });
  // 登录结果
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_login_result,
    async (rs: any) => {
      console.error("--登录结果", rs);
      if (rs.result == 2) {
        console.error("登录异常");
        User(pinia).setHasLogin(false);
        Local.remove("user");
        location.reload();
      }
    }
  );
  // 异地登录提醒
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_diff_loc_login_notification,
    diffOfflineFunc
  );
  //获取第三方游戏返回url
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_3rd_game_login_result,
    gameUrlResult
  );

  // 请求收藏的游戏id集合
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_all_collected, resAllCollect);
  // 添加收藏
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_modify_collect, resCollect);
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_send_system_notice,
    onHander_system_notice
  );
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_sys_msg, onHandler_system_msg);


  // 用户信息
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_roleinfo_msg, handleRoleInfo);
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_user_info, handleUserInfo);

  // 回执监听
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_email_list, handleEmailInfo);
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_vip_info, handleVipInfo);
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_money_update2,
    handleUpdateMoney
  );
  // 用户金额变化后，重新拉取金额
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_roleinfo_with_id,
    handleUpdateRoleInfo
  );
  // 充值成功
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_recharge_success_from_third,
    handleDepositSuc
  );
  // 监听新邮件
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_new_email, handleNewEmail);
  // 登录完成
  MessageEvent2.addMsgEvent(10086, handleLoginFinish);
  // 获取充值方式列表
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_req_get_shop_info, handleShopInfoRes);
  // 提现
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_bank_card_info_list, handleMyBankList);
});
onMounted(async () => {
  init(String(route.name));

  Local.set("agentid", route.query.uid || "0");
});

watch(
  () => shopInfoData.value,
  (n: any) => {
    state.isMainDeposit = n.rechargelist_by_paymenttype.every((item: any) => !item.status); // 是否全部充值方式都维护
    if (state.isMainDeposit) {
      state.walletList.forEach((item: any) => {
        if (item?.key === 'deposit') {
          item.img = "/imgs/tabbar/cz_close.webp";
        }
      })
    }
  }
);
watch(
  () => bankCardInfoList.value,
  (n: any) => {
    state.isMainWidthdraw = !n.bank_card_maintain_status && !n.usdt_maintain_status; // 是否全部提现方式都维护
    if (state.isMainWidthdraw) {
      state.walletList.forEach((item: any) => {
        if (item?.key === 'withdrawals') {
          item.img = "/imgs/tabbar/tx_close.webp";
        }
      })
    }
  }
);

watch(
  () => route.name,
  (n: any) => {
    init(String(n));

    if (n != "openGame") {
      let event = "onorientationchange" in window ? "orientationchange" : "resize";
      window.addEventListener(event, resizeChange, false);
    }
  }
);

</script>
<style lang="scss" scoped>
.app {
  // min-height: 100vh;
  user-select: none !important;
  position: relative;
  display: flex;
  flex-direction: column;

  .app_bg {
    position: absolute;
    height: 300px;
    width: 100%;
    top: 0;
    pointer-events: none;
    // background: linear-gradient(180deg, rgba(255, 45, 45, 0.18) 0%, rgba(255, 45, 45, 0.12) 42.86%, rgba(255, 45, 45, 0.00) 100%);
  }

  .amount_box {
    display: flex;
    align-items: center;

    >span {
      margin: 0 6px;
    }
  }

  .placeholder {
    height: 44px;
  }

  :deep(.nut-tabbar) {
    background-color: #100e26;
    border: none;

    &::before {
      content: "";
      width: 100%;
      height: 30px;

      // background-color: red;
      position: absolute;
      top: -18px;
      left: 50%;
      transform: translateX(-50%);
      background-image: url(/imgs/home/tabbar_bg.png);
      background-size: cover;
      background-position: center;
      z-index: -1;
    }
  }

  .tt {
    display: inline-block;
    z-index: 1;
    width: 40px;
    height: 40px;
    position: absolute;
    top: -40px;
    left: 50%;
    transform: translateX(-50%);
  }
}

.login_pop {
  display: flex;
  width: 355px;
  height: 100%;
  margin: 0 auto;
  align-items: center;
  justify-content: center;
}

.diff_offline_dialog {
  padding: 24px 20px 30px 20px;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  line-height: 21px;

  .btn {
    width: 100%;
    margin-top: 24px;
    height: 44px;
    background: linear-gradient(180deg, #5567ff 0%, #9e1eff 100%);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 14px;
    font-weight: 500;
    line-height: 14px;
  }
}

.nut-tabbar-item__icon--unactive {
  color: #fff !important;
}

.nut-tabbar-item {
  color: #5d69ff;
  margin-bottom: 7px;
  align-items: end;
  /* background-color: #301a73; */
}

.item {
  height: 35px;
}

:deep(.nut-popover .nut-popover-content) {
  //opacity: none;
}

.tab_style {
  width: 32px;
}

.popover_bg {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 0;
  background: linear-gradient(180deg, #131232 6.18%, #100e26 100%);
  border-radius: 6px;
  // background-size: 100% 100%;
  display: flex;
  justify-content: space-around;
  transition: all 1s;
  z-index: 99;
  border-top: 1px solid transparent;
  border-image: linear-gradient(to right, transparent, white, transparent) 1;

  >div {
    display: flex;
    flex-direction: column;
    margin-top: 12px;
    color: #8e82c2;
    align-items: center;

    >img {
      width: 38px;
      height: 38px;
    }
  }
}

.pop_height {
  height: calc(env(safe-area-inset-bottom) + 165px);
}
</style>
